package com.hotau.product;

import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.framework.RightBtnVisible;
import com.hotau.location.WebImageView;
import com.hotau.product.vo.Comment;
import com.hotau.product.vo.CommentStatics;
import com.hotau.product.vo.Product;
import com.hotau.product.vo.ProductDetail;
import com.hotau.ui.Pull2RefreshView;
import com.hotau.ui.Pull2RefreshView.OnRefreshListener;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpRequestAsynTask;
import com.hotau.util.HttpUtil;
import com.hotau.util.JsonParserUtil;

public class ProductDetailFragment extends Fragment implements
		OnItemClickListener, RightBtnVisible, OnRefreshListener, Serializable, OnClickListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public List<String> listname;
	public List<String> listprice;
	public List<String> listbreakfast;
	public List<String> listpaytype;
	public List<String> listbroadBand;

	private Product product;
	private ProductDetail productDetail;
	private View headerView;
	private ArrayList<Comment> comments;
	private CommentAdapter adapter;
	private CommentStatics commentStatics;
	private boolean needUpdateComment;

	private static final String SPERATOR = "----------SPERATOR---------";

	public LinearLayout roomInforView;
	private Pull2RefreshView refreshView;
	private Button addToCartBtn;
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
		
		Bundle dataBundle = getArguments();
		if(dataBundle != null) {
			product = (Product)dataBundle.getSerializable("product");	
		}
		return inflater.inflate(R.layout.product_poi_detail_list, container, false);
	}
	
	public void setNeedUpdateComment(boolean needUpdateComment) {
		this.needUpdateComment = needUpdateComment;
	}

	// public void onResume()
	// {
	// super.onResume();
	//
	// if(poi.latitude != 0)
	// {
	// HotauActivity csmbpActivity = (HotauActivity) getActivity();
	// Button btn = csmbpActivity.getRightButton();
	// btn.setOnClickListener(new OnClickListener()
	// {
	// @Override
	// public void onClick(View v)
	// {
	// ArrayList<Poi> pois = new ArrayList<Poi>();
	// pois.add(poi);
	// HNAPAYActivity csmbpActivity = (HNAPAYActivity) getActivity();
	// csmbpActivity.pushFragment("地图", new PoiMapFragment(pois));
	// }
	// });
	//
	// btn.setVisibility(View.VISIBLE);
	// btn.setText("地图模式");
	// }
	// }

	private void setTextViewValue(View rootView, int textId, String preStr, String value) {
		if (StringUtils.isBlank(value)) {
			rootView.findViewById(textId).setVisibility(View.GONE);
		} else {
			if (preStr != null) {
				value = preStr + value;
			}
			((TextView) rootView.findViewById(textId)).setText(value);
		}
	}

	private void setTextViewValue(int textId, String preStr, String value) {
		this.setTextViewValue(headerView, textId, preStr, value);
	}

	private void setTextViewValue(int textId, String value) {
		this.setTextViewValue(textId, null, value);
	}

	private void setTextViewHtmlValue(View rootView, int textId, String preStr,
			String value, String color) {
		if (value == null) {
			value = "暂无";
		}

		if (preStr != null) {
			value = preStr + "<font color='" + color + "'>" + value + "</font>";
		}

		((TextView) rootView.findViewById(textId)).setText(Html.fromHtml(value));
	}

	private void updateCommentStatics() {
		if (this.getActivity().findViewById(R.id.product_detail_comment) != null) {
			TextView comment = (TextView) this.getActivity().findViewById(R.id.product_detail_comment);
			comment.setText(Html.fromHtml("点评( <font color='blue'>" + commentStatics.commentCount + "</font> )"));
		}
	}

	private String generateImageUrl(String file) {
		if (file.startsWith("/")) {
			file = file.substring(1);
		}

		String[] names = file.split("/");
		file = file.substring(0, file.lastIndexOf(names[names.length - 1]));

		String fileUrl = HotauConstants.HOTAU_HOST_ROOT_URL
				+ file.concat(URLEncoder.encode(names[names.length - 1]));
		Log.d("mytag", "image url: " + fileUrl);

		return fileUrl;
	}

	private int getSellerStarImageByStar(int star) {
		int resId = 0;
		if (star == 2) {
			resId = R.drawable.hotel_2star;
		} else if (star == 3) {
			resId = R.drawable.hotel_3star;
		} else if (star == 4) {
			resId = R.drawable.hotel_4star;
		} else if (star == 5) {
			resId = R.drawable.hotel_5star;
		}

		return resId;
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setHasOptionsMenu(true);
		refreshView = (Pull2RefreshView) getActivity().findViewById(R.id.location_comment_list);
		refreshView.enableRefresh(false);
		headerView = LayoutInflater.from(getActivity()).inflate(R.layout.product_item_detail, null, false);
		refreshView.getListView().addHeaderView(headerView, null, false);
		
		((Button) headerView.findViewById(R.id.product_detail_call))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + productDetail.telphone));
						getActivity().startActivity(intent);
					}
				});

		((Button) getActivity().findViewById(R.id.product_comment_btn))
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Bundle bundle = new Bundle();
						bundle.putSerializable("product", product);
						bundle.putSerializable("productDetailFragment", ProductDetailFragment.this);
						AddCommentFragment fragment = new AddCommentFragment();
						fragment.setArguments(bundle);
						
						HotauActivity csmbpActivity = (HotauActivity) getActivity();
						csmbpActivity.pushFragment("我要点评", fragment);
					}
				});
		
		addToCartBtn = (Button)getActivity().findViewById(R.id.add_to_cart);
		addToCartBtn.setOnClickListener(this);
		
		LinearLayout detailLayout = (LinearLayout)getActivity().findViewById(R.id.detailLayout);
		RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)detailLayout.getLayoutParams();
		params.height = HotauActivity.window_height - addToCartBtn.getLayoutParams().height;
		detailLayout.setLayoutParams(params);
		
		if (this.productDetail == null) {
			mockProductDetail();//模拟详情
			mockComment();//模拟数据
//			doRequest();
//			this.comments = new ArrayList<Comment>();
		} else {
			if (needUpdateComment) {
				pageNo = totalPageNo = 1;
//				this.doRequestComment();
				needUpdateComment = false;
			}
			this.updateView();
		}
		
		ListView listView = refreshView.getListView();
		listView.setCacheColorHint(0);
		listView.setDivider(getActivity().getResources().getDrawable(R.drawable.location_item_split));
		refreshView.setRefreshListener(this);
		refreshView.hasMore(pageNo < totalPageNo);
		listView.setOnItemClickListener(this);
		adapter = new CommentAdapter();
		listView.setAdapter(adapter);
	}

	private int pageNo = 1;
	private int totalPageNo = pageNo;

	private void parseProductDetail(String result) {
		Log.d("mytag", "parseProductDetail: " + result);
		productDetail = (ProductDetail) JsonParserUtil.str2Object(result, ProductDetail.class);
		if (productDetail != null && productDetail.errorMsg == null) {
			if (productDetail instanceof ProductDetail) {
				
			}
			updateView();
		} else {
			if (productDetail != null) {
				DialogUtil.showDialog(getActivity(), "提示", productDetail.errorMsg);
			} else {
				DialogUtil.showDialog(getActivity(), "提示", "网络错误！");
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void parseComments(String result) {
		Log.d("mytag", "parseComments: " + result);
		refreshView.onRefreshComplete();
		commentStatics = (CommentStatics) JsonParserUtil.str2Object(result, CommentStatics.class);
		if (commentStatics != null && commentStatics.isSuccess()) {
			ArrayList<Comment> comments = (ArrayList<Comment>) JsonParserUtil
					.str2ObjectByTag(result, "allComment", 
							new TypeReference<ArrayList<Comment>>() {});

			pageNo = commentStatics.currentPageNo;
			totalPageNo = commentStatics.totalPageNo;
			refreshView.hasMore(pageNo < totalPageNo);

			if (pageNo > 1) {
				this.comments.addAll(comments);
			} else {
				this.comments = comments;
			}
			commentStatics.comments = this.comments;

			adapter.notifyDataSetChanged();
			updateCommentStatics();
			// ((TextView)
			// headerView.findViewById(R.id.location_detail_comment)).setText("点评("
			// + commentStatics.commentCount + ")");
		} else {
			if (commentStatics != null) {
				DialogUtil.showDialog(getActivity(), "提示", commentStatics.errorMsg);
			} else {
				DialogUtil.showDialog(getActivity(), "提示", "网络错误！");
			}
		}
	}

	class ProductDetailTask extends HttpRequestAsynTask {
		public ProductDetailTask(Context context) {
			super(context);
		}

		@Override
		protected void doPostExecute(String result) {
			Log.i("poiDetail", result);
			String[] strs = result.split(SPERATOR);
			if (strs != null && strs.length == 2) {
				parseProductDetail(strs[0]);
				parseComments(strs[1]);
			} else {
				DialogUtil.showDialog(getActivity(), "提示", "网络错误！");
			}

		}

		protected String doInBackground(String... params) {
			String result = "测试结果";
			if (!HotauConstants.DEMO) {
				result = HttpUtil.doWrapedHttp(context, new String[] { params[0], params[1], params[2], params[3] });
				result += SPERATOR + HttpUtil.doWrapedHttp(context, new String[] {params[4], params[5], params[6], params[7] });
			}
			return result;
		}
	}

	private void initDetailParams(String[] strs) {
		String url = null;

		String request = "Form:productId=" + product.getProductId() + ";terminalCode="
				+ HotauConstants.getTerminalCode(getActivity());
		strs[0] = url;
		strs[1] = request;
		strs[2] = HttpUtil.UTF8_ENCODING;
		strs[3] = HttpUtil.HTTP_POST;
	}

	private void initCommentsParams(String[] strs) {
		String url = HotauConstants.LOCATION_QUERY_COMMENT;
		String request = "Form:productId=" + product.getProductId() + ";pageNo=" + pageNo + ";terminalCode=" + HotauConstants.getTerminalCode(getActivity());
		strs[4] = url;
		strs[5] = request;
		strs[6] = HttpUtil.UTF8_ENCODING;
		strs[7] = HttpUtil.HTTP_POST;
	}

	private void doRequest() {
		String[] strs = new String[8];
		this.initDetailParams(strs);
		this.initCommentsParams(strs);
		ProductDetailTask task = new ProductDetailTask(this.getActivity());
		task.setLockScreen(false);
		task.execute(strs);
	}

	private void doRequestComment() {
		String url = HotauConstants.LOCATION_QUERY_COMMENT;

		HttpRequestAsynTask task = new HttpRequestAsynTask(getActivity()) {
			
			@SuppressWarnings("unchecked")
			@Override
			protected void doPostExecute(String result) {
				refreshView.onRefreshComplete();
				commentStatics = (CommentStatics) JsonParserUtil.str2Object(result, CommentStatics.class);
				if (commentStatics != null && commentStatics.isSuccess()) {
					ArrayList<Comment> cos = (ArrayList<Comment>) JsonParserUtil
							.str2ObjectByTag(result, "allComment",
									new TypeReference<ArrayList<Comment>>() {});

					pageNo = commentStatics.currentPageNo;
					totalPageNo = commentStatics.totalPageNo;
					refreshView.hasMore(pageNo < totalPageNo);

					if (pageNo > 1) {
						comments.addAll(cos);
					} else {
						comments = cos;
					}

					commentStatics.comments = comments;

					adapter.notifyDataSetChanged();
					updateCommentStatics();
					// ((TextView)
					// headerView.findViewById(R.id.location_detail_comment)).setText("点评("
					// + commentStatics.commentCount + ")");
				} else {
					if (commentStatics != null) {
						DialogUtil.showDialog(getActivity(), "提示", commentStatics.errorMsg);
					} else {
						DialogUtil.showDialog(getActivity(), "提示", "网络错误！");
					}
				}
			}
		};

		task.setLockScreen(false);

		// CommentRequest commentRequest = new CommentRequest();
		// commentRequest.productType = poi.type;
		// commentRequest.productId = poi.productId;
		// String actualRequest = JsonParserUtil.Object2JsonStr(commentRequest);
		// 发起http异步请求－3：真正发起请求
		String actualRequest = "Form:productId=" + product.getProductId()
				+ ";pageNo=" + pageNo
				+ ";terminalCode="
				+ HotauConstants.getTerminalCode(getActivity());
		Log.d("mytag", "actualrequest =" + actualRequest);
		task.execute(url, actualRequest, HttpUtil.UTF8_ENCODING,
				HttpUtil.HTTP_POST);
	}
	
	public void updateView() {
		getActivity().findViewById(R.id.product_detail_main).setVisibility(View.VISIBLE);

		if (StringUtils.isNotBlank(productDetail.image1)) {
			((WebImageView) headerView.findViewById(R.id.product_detail_icon))
					.setImageFromURL(generateImageUrl(productDetail.image1));
		}

		this.setTextViewValue(R.id.product_detail_title, productDetail.productName);
		this.setTextViewValue(R.id.product_detail_price_hint, "价格");
		this.setTextViewValue(R.id.product_detail_price, "￥", productDetail.price);

		((RatingBar) headerView.findViewById(R.id.product_detail_rate))
				.setRating(productDetail.getRateTol());

		if (product.getDistance() != null && product.getDistance() >= 0) {
			((TextView) headerView.findViewById(R.id.product_detail_distance))
					.setText(String.format("%d", (int) product.getDistance()) + "m");
		}

		this.setTextViewValue(R.id.product_detail_serviceprovider, productDetail.serviceProvider);
		this.setTextViewValue(R.id.product_detail_address, "地址:", productDetail.address);
		if (StringUtils.isNotBlank(productDetail.telphone)) {
			headerView.findViewById(R.id.product_detail_phone_container).setVisibility(View.VISIBLE);
			this.setTextViewHtmlValue(headerView, R.id.product_detail_call, "联系电话:", productDetail.telphone, "#0034ff");
		} else {
			headerView.findViewById(R.id.product_detail_phone_container).setVisibility(View.GONE);
		}

		this.setTextViewValue(R.id.product_detail_feature, "宝贝特色:", productDetail.feature);
		headerView.findViewById(R.id.product_detail_travel_info).setVisibility(View.GONE);
		this.setTextViewValue(R.id.product_detail_promote, "优惠信息:", productDetail.promote);

		int resId = getSellerStarImageByStar(product.getStarRate());
		ImageView imageView = (ImageView) this.headerView.findViewById(R.id.product_detail_promote_image);
		if (resId != 0) {
			imageView.setVisibility(View.VISIBLE);
			imageView.setImageResource(resId);
		} else {
			imageView.setVisibility(View.GONE);
		}

		if (commentStatics != null) {
			updateCommentStatics();
		}
	}
	
	private void mockProductDetail() {
		productDetail = new ProductDetail();
		productDetail.productName = product.getProductName();
		productDetail.price = String.valueOf(10);
		productDetail.rate = String.valueOf(product.getRateCount());
		productDetail.serviceProvider = "阿斯顿法师打发士大夫撒";
		productDetail.address = "白运区握山南二街5号";
		productDetail.telphone = "13822212981";
		productDetail.feature = "阿打发打发斯蒂芬暗色阿迪飞洒地方阿斯蒂芬啊打发";
		productDetail.promote = "买十份送一份";
		updateView();
	}

	private void mockComment() {
		comments = new ArrayList<Comment>();
		Comment comment = new Comment();
		comment.commentUserId = "哈啊哈";
		comment.commentDate = "2011-12-09 12:00";
		comment.comment1Count = "4";
		comment.commentContent = "很好好强大";
		
		Comment comment1 = new Comment();
		comment1.commentUserId = "哈啊哈";
		comment1.commentDate = "2011-12-09 12:00";
		comment1.comment1Count = "4";
		comment1.commentContent = "很好好强大";
		
		Comment comment2 = new Comment();
		comment2.commentUserId = "哈啊哈";
		comment2.commentDate = "2011-12-09 12:00";
		comment2.comment1Count = "4";
		comment2.commentContent = "很好好强大";
		
		comments.add(comment);
		comments.add(comment1);
		comments.add(comment2);
	}

	class CommentAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return comments == null ? 0 : comments.size();
		}

		@Override
		public Object getItem(int position) {
			return comments.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.product_comment_item, null);
				holder = new ViewHolder();
				// holder.iconView = (ImageView)
				// convertView.findViewById(R.id.location_comment_item_image);
				holder.userNameView = (TextView) convertView.findViewById(R.id.product_comment_item_username);
				holder.descriptionView = (TextView) convertView.findViewById(R.id.product_comment_item_description);
				holder.timeView = (TextView) convertView.findViewById(R.id.product_comment_item_time);
				holder.ratingBar = (RatingBar) convertView.findViewById(R.id.product_comment_item_rate);
				holder.replayCommentView = (TextView) convertView.findViewById(R.id.product_comment_reply_content);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			Comment comment = (Comment) this.getItem(position);
			holder.userNameView.setText(comment.commentUserId);
			holder.timeView.setText(comment.commentDate);
			holder.descriptionView.setText(comment.commentContext);
			holder.ratingBar.setRating(comment.getComment1Count());

			if (StringUtils.isBlank(comment.replyContext)) {
				convertView.findViewById(R.id.product_comment_reply_header).setVisibility(View.GONE);
				convertView.findViewById(R.id.product_comment_reply_content).setVisibility(View.GONE);
				convertView.findViewById(R.id.product_comment_reply_footer).setVisibility(View.GONE);
			} else {
				holder.replayCommentView.setText(comment.replyContext);
				convertView.findViewById(R.id.product_comment_reply_header).setVisibility(View.VISIBLE);
				convertView.findViewById(R.id.product_comment_reply_content).setVisibility(View.VISIBLE);
				convertView.findViewById(R.id.product_comment_reply_footer).setVisibility(View.VISIBLE);
			}
			return convertView;
		}

		class ViewHolder {
			// ImageView iconView;
			TextView userNameView;
			TextView descriptionView;
			TextView timeView;
			RatingBar ratingBar;
			TextView replayCommentView;
		}
	}
	
	@Override
	public void onClick(View arg0) {
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// HNAPAYActivity activity = (HNAPAYActivity) this.getActivity();

		// activity.pushFragment("点评内容", new
		// CommentDetailFragment(comments.get(arg2 - 1)));
	}

	@Override
	public void processRightBtn(Context context, Button rightBtn) {
		rightBtn.setText("地图");
		rightBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				go2Map();
			}
		});
	}

	private void go2Map() {
//		if (poi.getLatitude() != 0) {
//			ArrayList<Poi> pois = new ArrayList<Poi>();
//			poi.telphone = productDetail.telphone;
//			pois.add(poi);
//			HNAPAYActivity csmbpActivity = (HNAPAYActivity) getActivity();
//			csmbpActivity.pushFragment(poi.productName,
//					new PoiMapFragment(pois));
//		}
	}

	@Override
	public void onRefresh() {
		
	}

	@Override
	public void onLoadingMore() {
		this.pageNo++;
		this.doRequestComment();
	}
}
